package com.itheima.aduit.service.impl;

import com.itheima.aduit.service.ProcessService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author qiankaofei
 * @version 1.0
 * @date 2020/12/19 17:47
 */
@Service
public class ProcessServiceImpl implements ProcessService {

    /**
     * 资源对象
     */
    @Autowired
    private RepositoryService repositoryService;

    /**
     *  部署流程文件
     * @param file  上传的bpmn文件
     * @param companyId   企业id
     */
    @Override
    public void deployProcess(MultipartFile file,String companyId) throws IOException {
        //1. 获取文件名
        String fileName=file.getOriginalFilename();

        Deployment deploy = repositoryService.createDeployment().addBytes(fileName, file.getBytes())
                .tenantId(companyId)
                .deploy();
        System.out.println("deploy.getId() = " + deploy.getId());

    }

    /**
     * 查询所有的流程定义
     */
    @Override
    public List<ProcessDefinition> definitionList(String companyId) {
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().processDefinitionTenantId(companyId).latestVersion().list();
        if(CollectionUtils.isEmpty(list)){
            return new ArrayList<ProcessDefinition>(0);
        }
        return list;
    }

    /**
     * 设置流程的挂起与激活
     */
    @Override
    public void setSuspendProcess(String processKey, String companyId) {
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().processDefinitionTenantId(companyId)
                .processDefinitionKey(processKey).latestVersion().singleResult();

        boolean suspended = definition.isSuspended();
        if(BooleanUtils.isTrue(suspended)){
            // 挂起状态设置为激活
            repositoryService.activateProcessDefinitionById(definition.getId());
        }else{
            // 激活状态设置为挂起
            repositoryService.suspendProcessDefinitionById(definition.getId());
        }

    }
}
